10. Template `variables` and JS's `with`

Template variables and JS's with

Template variables and JS's with

Reading blog posts and tutorials online you'll see a lot of templates like this:

// index.html
<script type="text/template" id="menuItem-template">
    <td><a href="#item/<%= id %>"><%= name %></a></td>
    <td><%= rating %></td>
    <td><%= calories %></td>
    <td>
        <button class="select-item">Select Item</button>
    </td>
</script>

Notice that inside the template delimiters, first class variables are being used. This is different from what we just looked at where the data came from the properties of the menuItem object, like this:

// index.html
<script type="text/template" id="menuItem-template">
    <td><a href="#item/<%= menuItem.id %>"><%= menuItem.name %></a></td>
    <td><%= menuItem.rating %></td>
    <td><%= menuItem.calories %></td>
    <td>
        <button class="select-item">Select Item</button>
    </td>
</script>

The reason that we have access to the menuItem object and then use its properties is because we passed it along in the settings.

// app.js
...
template: _.template($('#menuItem-template').html(), {variable: 'menuItem'}),

render: function(id) {
    this.$el.html(this.template(this.model.attributes));
    return this;
},
...

See how a settings object is being passed to the template function? This settings object is used in the creation of the constructor function.

Without this function, Backbone resorts to using JavaScript's with block. A with block extends the scope chain for the statements that are within its block. with blocks are not recommended and are not allowed in strict mode.

When creating Backbone templates, make sure to access your data as properties on an object, and to pass that object name in with the template's settings.

Further Research